﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;

namespace ALDIOrganizer
{
    public partial class OpenFiles : Form
    {        
        bool _SQLChoiceEnabled;

        public OpenFiles()
        {
            InitializeComponent();
            SetEventHandlers();
            PopulateMRULists(true, true);
        }

        private void PopulateList(ListBox pListBox, List<string> pDataSource)
        {
            pListBox.DataSource = pDataSource.Count > 0 ?
                pDataSource :
                null;
            if (pListBox.DataSource == null)
            {
                // why manually??
                // a question to .NET creators. it doesn't work automatically for some reason.
                // same thing below.
                pListBox.Items.Clear();
            }
        }

        private void PopulateMRULists(bool pSQLiteList, bool pRotasList)
        {
            if (pSQLiteList)
            {
                PopulateList(
                    lbxSQLiteMRU,
                    Program.MRUSQLFiles.GetList);                
            }
            if (pRotasList)
            {
                PopulateList(
                    lbxRotasMRU,
                    Program.MRURotasFiles.GetList);                
            }
        }

        static void SetRadioButtons(RadioButton pCreate, RadioButton pOpen, OpenFileMode pHow)
        {
            if (pHow != OpenFileMode.CreateOrOpen)
            {
                pCreate.Checked = pHow.CreateEnabled();
                pOpen.Checked = !pHow.CreateEnabled();
            }
            pCreate.Enabled = pHow.CreateEnabled();
            pOpen.Enabled = pHow.OpenEnabled();
            
        }

        public OpenFiles(string pSQLPathFileName,
            string pRotaPathFileName,
            OpenFileFormMode pMode)
            : this()
        {
            if (!pMode.IsValid)
            {
                return;
            }
            if (pSQLPathFileName != String.Empty)
            {
                tbSQLFileName.Text = pSQLPathFileName;                
            }
            else if (lbxSQLiteMRU.Items.Count > 0)
            {
                lbxSQLiteMRU.SelectedIndex = 0;
            }
              
            if (pRotaPathFileName != String.Empty)
            {
                tbRotasFileName.Text = pRotaPathFileName;
            }
            else if (lbxRotasMRU.Items.Count > 0)
            {
                lbxRotasMRU.SelectedIndex = 0;
            }

            rbSQLOpenExisting.Enabled = pMode.SQLiteOpenEnabled;

            SetRadioButtons(rbSQLCreateNew, rbSQLOpenExisting, pMode.SQLiteFile);
            SetRadioButtons(rbRotasCreateNew, rbRotasOpenExisting, pMode.RotasFile);
            
            _SQLChoiceEnabled = (pMode.SQLiteFile != OpenFileMode.ChoiceDisabled);
            gbSQLite.Enabled = _SQLChoiceEnabled;
            VerifyFileNames();
        }
            

        void SetEventHandlers()
        {
            tbSQLFileName.TextChanged += TextBox_TextChanged;
            tbRotasFileName.TextChanged += TextBox_TextChanged;
            btnSQLBrowse.Click += Browse_Click;
            btnRotasBrowse.Click += Browse_Click;

            #region radio buttons (create new / Open existing)
            foreach (var radiobutton in new[]
                                            {
                                                rbSQLCreateNew,
                                                rbSQLOpenExisting,
                                                rbRotasCreateNew,
                                                rbRotasOpenExisting
                                            })
            {
                radiobutton.CheckedChanged += (sender, e) =>
                                                  {
                                                      rbRotasOpenExisting.Enabled = !rbSQLCreateNew.Checked;
                                                      if (rbSQLCreateNew.Checked)
                                                      {
                                                          rbRotasCreateNew.Checked = true;
                                                          rbRotasOpenExisting.Checked = false;
                                                      }
                                                      VerifyFileNames();
                                                  };
            }
            #endregion

            #region "most recently used" listboxes
            lbxRotasMRU.SelectedIndexChanged += MostRecentlyUsedListBox_SelectedIndexChanged;
            lbxSQLiteMRU.SelectedIndexChanged += MostRecentlyUsedListBox_SelectedIndexChanged;
            #endregion
        }

        void MostRecentlyUsedListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var _me = sender as ListBox;
            if (_me == null)
            {
                return;
            }
            if (_me.SelectedValue == null)
            {
                return;
            }
            var _selected = _me.SelectedValue.ToString();
            if (_me == lbxSQLiteMRU)
            {
                tbSQLFileName.Text = _selected;
                tbSQLFileName.SelectionStart = tbSQLFileName.Text.Length;
                tbSQLFileName.SelectionLength = 0;
            }
            if (_me != lbxRotasMRU)
            {
                return;
            }
            tbRotasFileName.Text = _selected;
            tbRotasFileName.SelectionStart = tbRotasFileName.Text.Length;
            tbRotasFileName.SelectionLength = 0;
        }

        private string ExtractDirectory(TextBox pTextBox)
        {
            string dir;
            try
            {
                dir = Path.GetDirectoryName(pTextBox == null || pTextBox.Text.Trim() == String.Empty ?
                    String.Empty :
                    pTextBox.Text);
            }
            catch
            {
                // exception thrown if the textbox did not contain a legal path string
                dir = String.Empty;
            }
            if(!String.IsNullOrEmpty(dir) &&
                Directory.Exists(dir))
            {
                return dir;
            }
            if (pTextBox == tbSQLFileName &&
                Directory.Exists(SQLiteAccess.GetDefaultPath))
            {
                return SQLiteAccess.GetDefaultPath;
            }
            if(pTextBox == tbRotasFileName &&
                Directory.Exists(Program.GetDefaultPath))
            {
                return Program.GetDefaultPath;
            }
            return String.Empty;
        }

        void Browse_Click(object sender, EventArgs e)
        {
            #region Initial checks
            var me = sender as Button;
            if (me == null)
            {
                return;
            }                        
            #endregion

            var result = DialogResult.Cancel;

            if (me == btnSQLBrowse)
            {
                
                if (rbSQLOpenExisting.Checked)
                {
                    result = Program.ShowSQLOpenDialog(ExtractDirectory(tbSQLFileName));
                }
                else
                {
                    if (rbSQLCreateNew.Checked)
                    {
                        result = Program.ShowSQLSaveAsDialog(ExtractDirectory(tbSQLFileName));
                    }
                }
                if (result == DialogResult.OK)
                {
                    tbSQLFileName.Text = Program.GetSelectedFileName;
                }
            }
            else
            {
                if (me == btnRotasBrowse)
                {
                    if (rbRotasCreateNew.Checked)
                    {
                        result = Program.ShowRotaSaveAsDialog(ExtractDirectory(tbRotasFileName));
                    }
                    else
                        if (rbRotasOpenExisting.Checked)
                        {
                            result = Program.ShowRotaOpenDialog(ExtractDirectory(tbRotasFileName));
                        }
                }
                if (result == DialogResult.OK)
                {
                    tbRotasFileName.Text = Program.GetSelectedFileName;
                }
            }
        }

        void TextBox_TextChanged(object sender, EventArgs e)
        {
            VerifyFileNames();
        }

        void VerifyFileNames()
        {
            btnOK.Enabled = _AreFilenamesValid;
        }

        bool _AreFilenamesValid
        {
            get
            {
                /* If user wants to create a new CurrentFile file, this file should not exist.
                 * If user wants to Open one - it'pShift the other way round, this file MUST to exist.
                 * So When is the data invalid?
                 * If the logical value of File.Exists is DIFFERENT than the logical value of
                 * "user wants to Open a file".
                 * That'pShift why it'pShift simpliest to use an XOR operator: in C#, written as ^ */
                if (_SQLChoiceEnabled &
                    (rbSQLOpenExisting.Checked ^ File.Exists(tbSQLFileName.Text)))
                {
                    return false;
                }
                return !(rbRotasOpenExisting.Checked ^ File.Exists(tbRotasFileName.Text));
            }
        }

        internal string GetSQLiteChoice
        {
            get
            {
                return tbSQLFileName.Text;
            }
        }

        internal string GetRotasTemplatesChoice
        {
            get
            {
                return tbRotasFileName.Text;
            }
        }

        internal FileMode GetSQLiteFileMode
        {
            get
            {
                return rbSQLOpenExisting.Checked ? FileMode.Open : FileMode.Create;
            }
        }

        internal FileMode GetRotasFileMode
        {
            get
            {
                return rbRotasOpenExisting.Checked ? FileMode.Open : FileMode.Create;
            }
        }

        private void btnClearSQLiteMRU_Click(object sender, EventArgs e)
        {
            Program.MRUSQLFiles.ClearList(true);
            Program.MRUSQLFiles.LoadList();
            PopulateMRULists(true, false);
        }

        private void btnClearRotasMRU_Click(object sender, EventArgs e)
        {
            Program.MRURotasFiles.ClearList(true);
            Program.MRURotasFiles.LoadList();
            PopulateMRULists(false, true);
        }

        
    }
}
